<?php
/*
Plugin Name: posts2jogger
Plugin URI: n o n e
Description: Sends a part of new post to Jogger.pl
Version: 0.1
Author: Radosław "radmen" Mejer
Author URI: http://radmen.info/
License: MIT
*/

class Wp2Jogger {
  
  /**
   * Tablica z podstawowa konfiguracja pluginu
   *
   * @var array
   */
  private $mOptions;
  
  /**
   * Klucz pod ktorym trzymane sa konfigi
   * 
   * @var string
   */
  private $mOptionsKey = 'posts2jogger';
  
  /**
   * Rejestruje wszelkie potrzebny glupoty
   */
  public function __construct() {
    register_activation_hook(__FILE__, array($this, 'activate'));
    register_deactivation_hook( __FILE__, array($this, 'deactivate') );

    add_action('admin_menu', array($this, 'registerOptionsPage'));
    add_action('post_submitbox_misc_actions', array($this,'showConfirmBox'));
    add_filter('wp_insert_post_data', array($this, 'send2Jogger'), 1, 2);
    
    $this->mOptions = get_option($this->mOptionsKey);
  }
  
  /**
   * Akcja odpalana przez register_activation_hook
   */
  public function activate() {
    add_option($this->mOptionsKey, array(
      'jid' => '',
      'pass' => '',
      'blog_name' => '',
      'use_markdown' => false,
    ));
  }
  
  public function deactivate() {
    delete_option($this->mOptionsKey);
  }
  
  public function registerOptionsPage() {
    add_options_page('posts2jogger Configuration', 'posts2jogger', 'manage_options', 'posts-to-jogger-admin-page', array($this, 'optionsPage'));
  }
  
  private function updateOptions(array $pOptions) {
    update_option($this->mOptionsKey, $pOptions);
    $this->mOptions = get_option($this->mOptionsKey);
  }
  
  public function optionsPage() {
    
    // Check to see if user has adequate permission to access this page
    if (!current_user_can('manage_options')){
      wp_die( __('You do not have sufficient permissions to access this page.') );
    }
    
    if($_POST['options']) {
      $new_options = $_POST['posts2jogger_options'];
      $new_options['use_markdown'] = (bool) $new_options['use_markdown'];
      
      // Display saved message when options are updated.
      _e('<div id="message" class="updated fade"><p>post2jogger settings saved</p></div>');

      $this->updateOptions($new_options);
    }
    ?>
    <h1 style="margin-bottom: 40px;">posts2jogger</h1>
    <form method="post" action="">
      <h2>jabber</h2>
      <table>
        <tr>
          <td style="width: 200px;">jid</td>
          <td><input type="text" size="60" name="posts2jogger_options[jid]" value="<?php echo $this->mOptions['jid']; ?>" /></td>
        </tr>
        <tr>
          <td style="width: 200px;">password</td>
          <td><input type="password" size="60" name="posts2jogger_options[pass]" value="<?php echo $this->mOptions['pass']; ?>" /></td>
        </tr>
      </table>

      <h2>jogger.pl</h2>
      <table>
        <tr>
          <td style="width: 200px;">blog name (<small><b><i>name</i></b>.jogger.pl)</small></td>
          <td><input type="text" size="60" name="posts2jogger_options[blog_name]" value="<?php echo $this->mOptions['blog_name']; ?>" /></td>
        </tr>
        <tr>
          <td style="width: 200px;">używaj markdown</td>
          <td><input type="checkbox" size="60" name="posts2jogger_options[use_markdown]" <?php echo $this->mOptions['use_markdown'] ? 'checked="checked"' : ''; ?> /></td>
        </tr>
      </table>

      <input type="submit" name="options" class="button-primary" value="<?php _e('Save Changes') ?>" />
    </form>
    <?php
  }
  
  public function showConfirmBox() {
    global $post;
    
    // Add the checkbox, but only if the post is already published.
    if($post->post_status=='publish') { ?>
      <div class="misc-pub-section">
        <label for="post_to_jogger" class="selectit">
          <input style="min-width:25px;" name="post_to_jogger" type="checkbox" id="post_to_jogger" value="post_to_jogger" />
          <?php
            _e('Prześlij na jogger.pl <small>(<strong>uwaga!</strong> każdorazowe zaznaczenie oznacza wysłanie nowego posta!)</small>');
          ?>
        </label>
      </div>
      <?php
    }
  }
  
  /**
   * Wysyla fragment notki na Joggera
   * 
   * Dane przechodzace przez ta metode nie sa w zaden sposob modyfikowane
   * Metoda wykonywana jest tylko wtedy kiedy post zostal oznaczony jako publiczny, oraz zaznaczono opcje wyslania na jogger.pl
   *
   * @param array $pData
   * @param array $pPostExtendedData
   * @return array
   */
  public function send2Jogger(array $pData, array $pPostExtendedData) {
    
    if('publish' !== $pPostExtendedData['post_status'] || true === empty($pPostExtendedData['post_to_jogger'])) {
      return $pData;
    }
    
    // @TODO: wysylanie wiadomosci via Jabber
    $msg = $this->generateJabberMsg($pPostExtendedData);
    
    return $pData;
  }
  
  /**
   * Przygotowuje wiadomosc jaka zostanie wyslana do bota Joggerowego
   * 
   * Wiadomosc jest skladana z danych wyslanych w formularzu, obslugiwany jest tag Excerpt
   *
   * @param array $pPostExtendedData
   * @return string wygenerowana wiadomosc
   */
  private function generateJabberMsg(array $pPostExtendedData) {
    $tmp = array();
    
    foreach($pPostExtendedData['post_category'] as $cat_id) {
      $name = get_cat_name($cat_id);
      
      if(false === empty($name)) {
        $tmp[] = $name;
      }
    }
    
    $jabber_msg = "(tytul:{$pPostExtendedData['post_title']})\n";
    
    // @TODO: trzeba ustawic poziom publiczny, poki co testowo ustawilem na prywatny
    $jabber_msg .= "(poziom:1)\n";
    $jabber_msg .= "(komentarze:nie)\n";
    $jabber_msg .= "(tag:{$pPostExtendedData['tax_input']['post_tag']})\n";
    
    if(false === empty($tmp)) {
      $jabber_msg .= "(kategoria:".join(',', $tmp).")\n";
    }
    
    $tmp = explode('<!--more-->', $pPostExtendedData['post_content']);
    
    // najwyrazniej post ma tag <!--more--> jako tresc wysylanego posta bierzemy to co jest przed tym tagiem
    if(count($tmp) > 1) {
      $content = $tmp[0];
    }
    else {
      $tmp = explode("\n\r\n", $pPostExtendedData['post_content']);
      $tmp = array_map('trim', $tmp);
      
      $content = $tmp[0];
    }
    
    $content = strip_tags($content, '<a><b><i><u><strong>');
    $content = stripslashes($content);
    
    if(true === $this->mOptions['use_markdown']) {
      $content = $this->convert2Markdown($content);
    }
    
    $jabber_msg .= "{$content}\n\n";
    
    if(true === $this->mOptions['use_markdown']) {
      $jabber_msg .= "[Więcej]({$pPostExtendedData['guid']})\n";
    }
    else{
      $jabber_msg .= "<a href=\"{$pPostExtendedData['guid']}\">Więcej</a>\n";
    }
    
    return $jabber_msg;
  }
  
  /**
   * Konwertuje wszelkie linki do skladni markdown
   *
   * @param type $pContent
   * @return type 
   */
  private function convert2Markdown($pContent) {
    $pContent = preg_replace('#<a.+href="(.+?)".*?>(.+?)</a>#', '[\\2](\\1)', $pContent);
    
    return $pContent;
  }
  
}

new Wp2Jogger();

?>